<?php

/*
	aterr - a threaded forum system.

	Copyright (c) 2006 Chris Jenkinson <chris@starglade.org>.
	All rights reserved.

	aterr is licensed under the GNU General Public License.
	<http://opensource.org/licenses/gpl-license.php>
*/

define('INCLUDE_PATH', 'include/');
include INCLUDE_PATH . 'common.inc.php';

$forums = new forums(false);

$op = (!empty($_GET['op']) ? $_GET['op'] : '');
$sub = (!empty($_GET['sub']) ? $_GET['sub'] : '');
$format = (!empty($_GET['format']) ? $_GET['format'] : 'rss');

$last_modified = 0;
$items = array();

$tz = date('O');
$tz = substr($tz, 0, 3) . ':' . substr($tz, 3);

switch ($format)
{
	case 'atom':
		
		$format = 'atom';
		$tpl_file = 'atom-feed.tpl';
		
		break;
	
	default:
	case 'rss':
		
		$format = 'rss';
		$tpl_file = 'rss-feed.tpl';
		
		break;
}

$template = new template($tpl_file);

if ($forums->f_id)
{
	$f_array = array($forums->f_id);
}
else
{
	$f_array = explode(', ', $config['stats_forums']);
}

foreach ($f_array as $key => $f_id)
{
	$flags = permission::get_default_flags('forums', $f_id);

	if (!$flags & (F_FORUM_VIEW | F_POST_READ))
	{
		unset($f_array[$key]);
	}
}

if (empty($f_array))
{
	header('HTTP/1.1 404 Not Found');
	die();
}

$sql = 'SELECT f.*, c.*
	FROM forums f, for_categories c
	WHERE c.id = f.id
	AND f.id IN (%s)';

$sql = sprintf($sql, implode(', ', $f_array));

$db->sql_query($sql);
$db->sql_data($f_data);

foreach ($f_data as $forum)
{
	$template->add_block_vars($tpl_file, 'category', array(
		'TITLE' => $forum['title']
	));
}

if (false !== ($posts = $forums->select_forum_posts($f_array, $count, 0, 15, 'd.date DESC')))
{
	header('Content-type: text/xml; charset="utf-8"');
	
	foreach ($posts as $post)
	{
		if ($post['is_unapproved'])
		{
			continue;
		}
		
		if ($post['date'] > $last_modified)
		{
			$last_modified = $post['date'];
		}
		
		$link = 'http://' . $config['domain_name'] . $config['install_path'] . forums::furl('view', $post['fp_id']) . '#' . $post['d_id'];
		
		$template->add_block_vars($tpl_file, 'item', array(
			'CATEGORY' => $post['forum_title'],
			'CREATOR' => $post['username'],
			'DATE-ATOM' => date('Y-m-d\TH:i:s', $post['date']) . $tz,
			'DATE-RSS' => date('r', $post['date']),
			'DESCRIPTION' => trim(format_text($post['text'])),
			'ID' => $link,
			'LINK' => $link,
			'TITLE' => htmlspecialchars($post['title'])
		));
	}
}
else
{
	header('HTTP/1.1 404 Not Found');
	die();
}

$template->add_vars($tpl_file, array(
	'FEED_LAST_MODIFIED' => date('Y-m-d\TH:i:s', $last_modified) . $tz,
	'SELF_LINK' => 'http://' . $config['domain_name'] . feed_url($format, $forums->f_id),
	'SITE_TITLE' => $config['site_name'],
	'SITE_DESCRIPTION' => $config['site_desc'],
	'SITE_LINK' => 'http://' . $config['domain_name'] . $config['install_path'] . $forums->furl(),
	'SITE_WEBMASTER' => $config['contact_email'] . ' (' . $config['contact_name'] . ')'
));

$template->parse($tpl_file);
echo $template->output($tpl_file);

?>
